<?php


namespace App\Service;


use App\Web\Model\Attach as AttachModel;
use EchoPHP\File\File;
use EchoPHP\File\UploadedFile;
use Ramsey\Uuid\Uuid;

class FileHandler extends FileBase {

    protected $fileServerPath;
    protected $file;
    /**
     * 目标文件
     * @var File
     */
    protected $target;

    public function __construct($file) {
        parent::__construct();
        if ($file instanceof UploadedFile || $file instanceof File) {
            $this->file = $file;
        } else {
            $this->file = new File($file);
        }
        $this->fileServerPath = rtrim(FILESERVER, '/') . '/';
    }

    /**
     * 文件移动
     * @param string $destination 目的文件夹
     * @param bool $withHashPath
     * @param bool $keepOld
     * @return array
     * @throws \Exception
     */
    public function move($withHashPath = true, $destination = '', $keepOld = false) {
        $hashPath = $withHashPath ? $this->generateHashStorePath() : '';
        $destination = rtrim($destination, '/');
        $storePath = (empty($destination) ? 'common' : ($destination)) . $hashPath . '/';

        if ($this->file instanceof UploadedFile) {
            $fileExtension = $this->file->getClientOriginalExtension();
            $originalName = $this->file->getClientOriginalName();
        } else {
            $fileExtension = $this->file->getExtension();
            $originalName = $this->file->getFilename();
        }
        $fileName = $this->fileId . '.' . $fileExtension;
        //$storePath = $this->fileServerPath . $storePath;
        if ($keepOld) {
            $this->target = $this->file->copy($storePath, $fileName);
        } else {
            $this->target = $this->file->move($storePath, $fileName);
        }

        $targetRelativePath = substr($this->target->getPathname(), strlen($this->fileServerPath));

        $targetInfo = [
            'fileid' => $this->fileId,                      //附件id，uuid生成
            'originalname' => $originalName,                //原始文件名称
            'filename' => $this->target->getFilename(),     //移动后文件名称
            'path' => $this->target->getPath(),             //文件存储完整路径  文件完整存储路径，含文件服务器地址，不含文件名
            'relativepathname' => $targetRelativePath,      //文件存储相对路径  排除文件服务器路径之后的路径,含文件名
            'filesize' => $this->target->getSize(),         //文件大小  Byte 字节
        ];

        return $targetInfo;
    }

    /**
     * 文件复制
     * @param bool $withHashPath
     * @param string $destination
     * @return array
     * @throws \Exception
     */
    public function copy($withHashPath = true, $destination = '') {
        return $this->move($withHashPath, $destination, true);
    }

    /**
     * 获取目标文件操作句柄
     * @return File
     */
    public function getTarget() {
        return $this->target;
    }


}